<?php

namespace common\helpers;

use Yii;
use common\helpers\maths\Normdist;

/**
 * Description of MathHelper
 *
 * @author emhome
 */
class MathHelper {

    public static function bcmul($v1, $v2) {
        if (function_exists('bcmul')) {
            return bcmul($v1, $v2);
        }
        return (int) (($v1 * $v2 * 10) / 10);
    }

    public static function bccomp($v1, $v2) {
        if (function_exists('bccomp')) {
            return bccomp($v1, $v2, 2);
        } else {
            return intval(intval($v1 * 100) - intval($v2 * 100));
        }
    }

    public static function goodsPriceWeight2($price) {
        $path = Yii::getAlias('@common/data/temp.php');
        $data = require $path;
        $list = [];
        foreach ($data as $item) {
            list($p, $s) = $item;
            $temp = array_fill(count($list), $s, $p);
            $list += $temp;
        }
        return static::normdist($price, $list);
    }

    public static function goodsPriceWeight($price, $average, $stdDev) {
        $normdist = new Normdist([
            'average' => $average,
            'stdDev' => $stdDev
        ]);
        return $normdist->computed($price);
    }

    /**
     * @param number $n
     * @param array $data
     * @return number
     */
    public static function normdist($n, $data) {
        $normdist = new Normdist(['list' => $data]);
        return $normdist->computed($n);
    }

    /**
     * @name 获取平均值
     * @param array $array
     * @return number
     */
    public static function average($array) {
        $size = count($array);
        if (!$size) {
            return false;
        }
        return array_sum($array) / $size;
    }

    /**
     * 标准差
     * 方差的平方根（方差的正的平方根叫做标准差）
     * @param array $data
     * @return number
     */
    public static function stdDev($data) {
        $size = count($data);
        if ($size < 2) {
            return false;
        }
        $average = static::average($data);
        $total = 0;
        foreach ($data as $v) {
            $total += pow($v - $average, 2);
        }
        return sqrt($total / ($size - 1));
    }

}
